<template>
  <div class="supplier-list-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>供应商管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddSupplier">
          <el-icon><Plus /></el-icon> 新增供应商
        </el-button>
        <el-button type="default" @click="handleImport">
          <el-icon><Upload /></el-icon> 导入
        </el-button>
        <el-button type="default" @click="handleExport">
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>
    </div>

    <!-- 筛选条件区 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.name" placeholder="输入供应商名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="供应商编码">
          <el-input v-model="searchForm.code" placeholder="输入供应商编码" clearable></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="省份">
          <el-select v-model="searchForm.province" placeholder="全部省份" clearable>
            <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.code"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="supplierList"
        border
        stripe
        size="medium"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="code" label="供应商编码" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="供应商名称" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="contactPerson" label="联系人" min-width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" min-width="120"></el-table-column>
        <el-table-column prop="provinceName" label="省份" min-width="90"></el-table-column>
        <el-table-column prop="businessScope" label="经营范围" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" min-width="90">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" sortable></el-table-column>
        <el-table-column label="操作" min-width="140" fixed="right">
          <template #default="scope">
            <el-button size="small" type="text" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button size="small" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="text"
              :style="scope.row.status === 1 ? 'color: #f56c6c' : 'color: #409eff'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Plus, Upload, Download } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义供应商接口
interface SupplierItem {
  id: string;
  code: string;
  name: string;
  contactPerson: string;
  contactPhone: string;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  address: string;
  businessScope: string;
  status: 0 | 1;
  createTime: string;
  updateTime: string;
  remark?: string;
}

// 定义省份接口
interface ProvinceItem {
  code: string;
  name: string;
}

// 状态管理
const loading = ref(false);
const supplierList = ref<SupplierItem[]>([]);
const multipleSelection = ref<SupplierItem[]>([]);
const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: '',
  province: ''
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 省份数据
const provinces = ref<ProvinceItem[]>([
  { code: '330000', name: '浙江省' },
  { code: '110000', name: '北京市' },
  { code: '310000', name: '上海市' },
  { code: '440000', name: '广东省' },
  { code: '510000', name: '四川省' },
  { code: '420000', name: '湖北省' }
]);

// 选择项变化
const handleSelectionChange = (val: SupplierItem[]) => {
  multipleSelection.value = val;
};

// 搜索供应商
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchSupplierList();
};

// 重置表单
const resetForm = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    status: '',
    province: ''
  });
  pagination.currentPage = 1;
  fetchSupplierList();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchSupplierList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchSupplierList();
};

// 查看供应商详情
const handleViewDetail = (row: SupplierItem) => {
  router.push({ name: 'SupplierDetail', params: { id: row.id } });
};

// 编辑供应商
const handleEdit = (row: SupplierItem) => {
  router.push({ name: 'SupplierEdit', params: { id: row.id } });
};

// 新增供应商
const handleAddSupplier = () => {
  router.push({ name: 'SupplierAdd' });
};

// 切换供应商状态（启用/禁用）
const handleStatusChange = async (row: SupplierItem) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  const confirmMessage = `确定要${statusText}供应商【${row.name}】吗？`;

  try {
    await ElMessageBox.confirm(confirmMessage, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 模拟API请求
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 800));

    // 更新本地状态
    row.status = newStatus;
    ElMessage.success(`供应商已${statusText}`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`供应商${statusText}失败`);
      console.error(`供应商${statusText}失败:`, error);
    }
  } finally {
    loading.value = false;
  }
};

// 导入供应商
const handleImport = () => {
  // TODO: 实现导入功能
  ElMessage.info('导入功能开发中...');
};

// 导出供应商
const handleExport = () => {
  if (supplierList.value.length === 0) {
    ElMessage.warning('当前没有数据可导出');
    return;
  }
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中...');
};

// 获取供应商列表数据
const fetchSupplierList = async () => {
  loading.value = true;
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800));

    // 生成模拟数据
    const provinceList = provinces.value;
    const mockData: SupplierItem[] = Array.from({ length: pagination.pageSize }, (_, i) => {
      const province = provinceList[Math.floor(Math.random() * provinceList.length)];
      const status = Math.random() > 0.2 ? 1 : 0;
      return {
        id: `${pagination.currentPage}-${i + 1}`,
        code: `SP${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
        name: `供应商${Math.floor(Math.random() * 1000) + 1}`,
        contactPerson: `联系人${Math.floor(Math.random() * 100)}`,
        contactPhone: `13${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
        provinceCode: province.code,
        provinceName: province.name,
        cityCode: `${province.code.substring(0, 2)}0100`,
        cityName: `${province.name.substring(0, province.name.length - 1)}市`,
        address: `测试地址${Math.floor(Math.random() * 100)}号`,
        businessScope: ['办公用品', 'IT设备', '家具家电', '劳保用品', '五金工具'][Math.floor(Math.random() * 5)],
        status: status as 0 | 1,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 365) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
        updateTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' ')
      };
    });

    supplierList.value = mockData;
    pagination.total = 386; // 模拟总条数
  } catch (error) {
    ElMessage.error('获取供应商列表失败');
    console.error('获取供应商列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchSupplierList();
});
</script>

<style scoped lang="scss">
.supplier-list-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 10px;
}

.table-card {
  height: calc(100% - 180px);
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .supplier-list-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
}
</style>